<?php

namespace App\V3\V3_2_7\Services;

use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Models\AdminPermissionLimitModel;
use App\V3\V3_2_7\Models\CustomTagModel;
use App\V3\V3_2_7\Models\ModuleModel;
use App\V3\V3_2_7\Models\RoleSettingModel;
use App\V3\V3_2_7\Models\UserMenuModel;
use \Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserMenuService
{
    public static function edit($data): ?JsonResponse
    {
        DB::beginTransaction();
        try {
            $UserMenuModel = UserMenuModel::query();
            $userMenuInfo = $UserMenuModel->where([
                'user_id' => $data['user_id']
            ])->first();
            unset($data['time']);
            if (!empty($userMenuInfo)) {
                $UserMenuModel->where([
                    'user_id' => $data['user_id']
                ])->update($data);
            } else {
                $UserMenuModel->insertGetId($data);

            }
            DB::commit();
            return success();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('编辑用户菜单异常:' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }

    public static function info($data)
    {
        $menuInfo = UserMenuModel::query()->where([
            'user_id' => $data['user_id']
        ])->first();
        $flag = 0;
        $idArr = [];
        $uidArr = [];
        if (empty($menuInfo)) {
            if (!$data['user_type']) {
                $adminRole = AdminModel::query()->where([
                    'id' => $data['user_id']
                ])->value('admin_role');
                $roleInfo = RoleSettingModel::where('role_id', $adminRole)->first();
                $fModuleArr = array_filter(explode(',', $roleInfo['first_module']), function ($v) {
                    return $v !== '';
                });

                $sModuleArr = array_filter(explode(',', $roleInfo['second_module']), function ($v) {
                    return $v !== '';
                });
                $idArr = array_merge($fModuleArr, $sModuleArr);
            }
            if (!empty($idArr)) {
                $menuId = [66, 99, 100, 104, 112, 64, 63, 125, 126, 124, 127];
                $menuId = array_intersect($idArr, $menuId);
                $moduleList = ModuleModel::query()
                    ->select(
                        'id',
                        'module_name',
                        'icon as image',
                        'url2 as url'
                    )->whereIn('id', $menuId)->get();
                foreach ($moduleList as &$iVal) {
                    if (!empty($iVal['image'])) {
                        $iVal['image'] = 'https://img.smerp.top' . $iVal['image'];
                    }
                }
                $defJson = json_encode($moduleList, JSON_THROW_ON_ERROR | true);
                UserMenuModel::query()
                    ->insertGetId([
                        'phone_menu' => $defJson,
                        'user_id' => $data['user_id']
                    ]);
                $menuInfo['user_id'] = $data['user_id'];
                $menuInfo['phone_menu'] = $defJson;
            }
        } else {
            $flag = 1;
            $uidArr = AdminPermissionLimitModel::query()
                ->where('user_id', $data['user_id'])->pluck('module_id');
            $uidArr = $uidArr->toArray() ?? [];
        }
        if (!empty($menuInfo['phone_menu'])) {
            $phoneMenuArr = json_decode($menuInfo['phone_menu'], true, 512, JSON_THROW_ON_ERROR);
            $uMenuArr = [];
            foreach ($phoneMenuArr as &$mVal) {
                $mVal['full_name'] = $mVal['module_name'];
                if (!empty($mVal['label_id'])) {
                    $mVal['label_name'] = CustomTagModel::query()
                        ->where('id', $mVal['label_id'])
                        ->value('label_name') ?? '';
                    $mVal['full_name'] = $mVal['label_name'] . $mVal['module_name'];
                }
                if ($data['user_type']) {
                    $tequanIdArr = [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31];
                    if (!empty($uidArr)) {
                        if (!in_array($mVal['id'], $tequanIdArr, true)) {
                            if (in_array($mVal['id'], $uidArr, true)) {
                                $uMenuArr[] = $mVal;
                            }
                        } else {
                            $uMenuArr[] = $mVal;
                        }
                    } elseif (in_array($mVal['id'], $tequanIdArr, true)) {
                        $uMenuArr[] = $mVal;
                    }
                }
            }
            if (!empty($flag) && $data['user_type']) {
                $phoneMenuArr = $uMenuArr;
            }
            $menuInfo['phone_menu'] = $phoneMenuArr;
        }
        if (!empty($menuInfo['pc_menu'])) {
            $pcMenuArr = json_decode($menuInfo['pc_menu'], true);
            foreach ($pcMenuArr as &$cVal) {
                $cVal['full_name'] = $cVal['label_name'] . $cVal['module_name'];
            }
            $menuInfo['pc_menu'] = $pcMenuArr;
        }
        return $menuInfo ?? "";
    }
}
